package com.hongxun.budget.ui.activity.tk;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DMaterialModelItemEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.adapter.SpinnerAdapter;
import com.hongxun.budget.ui.dialog.NoticeDialog;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.TestingUtils;
import com.hongxun.entity.LoginInfo;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.DMaterialModelEntity;
import com.hongxun.greenentity.tk.DMaterialModelItemEntity;
import com.hongxun.interfaces.ClickListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

public class AddMaterialModelActivity extends BaseActivity {


    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.project_name)
    EditText projectName;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.spinner2)
    Spinner spinner2;
    @BindView(R.id.list)
    RecyclerView list;
    SpinnerAdapter<BDataDictionaryEntity> adapter1;
    SpinnerAdapter<String> adapter2;
    SuperAdapter<DMaterialModelItemEntity> adapter;

    DMaterialModelEntity d = null;//修改的d
    List<BDataDictionaryEntity> bDataDictionaryEntities;
    List<String> ranges = new ArrayList<>();
    List<DMaterialModelItemEntity> datas = new ArrayList<>();
    List<DMaterialModelItemEntity> deleteDatas = new ArrayList<>();
    DaoSession session;
    String guid;
    DMaterialModelItemEntity dm;//更换的材料

    @Override
    public int getLayoutId() {
        return R.layout.activity_add_material_model;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        session = GreenDaoManager.getInstance().getmDaoSession();
        rightSave.setVisibility(View.VISIBLE);
        guid = getIntent().getStringExtra("guid");
        if (guid != null) {
            d = session.getDMaterialModelEntityDao().load(guid);
        } else {
            guid = UUID.randomUUID().toString();
        }
        bDataDictionaryEntities = DBUtils.getBDataDictionaryEntities("material_model");
        spinner.setAdapter(adapter1 = new SpinnerAdapter<BDataDictionaryEntity>(context, bDataDictionaryEntities, spinner));
        ranges.add("自己");
        ranges.add("系统");
        spinner2.setAdapter(adapter2 = new SpinnerAdapter<String>(context, ranges, spinner2));
        list.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list.setAdapter(adapter = new SuperAdapter<DMaterialModelItemEntity>(R.layout.content_add_matrial_model) {
            @Override
            public void bindView(ViewHolder viewHolder, final DMaterialModelItemEntity itemEntity, final int i) {
                BMaterialEntity load = session.getBMaterialEntityDao().load(itemEntity.getMaterialGuid());
                ((TextView) viewHolder.getView(R.id.device_type)).setText(load.getMMidtype());
                ((TextView) viewHolder.getView(R.id.name)).setText(load.getMName());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(load.getMParameter());
                ((TextView) viewHolder.getView(R.id.unit)).setText(load.getMUnit());
                ((TextView) viewHolder.getView(R.id.count)).setText(itemEntity.getCount() + "");
                viewHolder.getView(R.id.delete_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        new NoticeDialog().setMsg("是否删除该材料?").setCancelButton("取消", null).setConfirmButton("删除", new ClickListener() {
                            @Override
                            public void click() {
                                deleteDatas.add(itemEntity);
                                datas.remove(i);
                                adapter.notifyDataSetChanged();
                            }
                        }).show(getFragmentManager(), "");
                    }
                });
                viewHolder.getView(R.id.change_old_device).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dm = itemEntity;
                        BMaterialEntity materialEntity = GreenDaoManager.getInstance().getmDaoSession().getBMaterialEntityDao().load(itemEntity.getMaterialGuid());
                        Intent intent = new Intent(activity, AddMaterialActivity.class);
                        intent.putExtra("label", materialEntity.getMBigtype());
                        intent.putExtra("change", true);
                        startActivityForResult(intent, 2);
                    }
                });
            }
        });
        adapter.setData(datas);
        adapter.setEmptyDataView(R.layout.view_empty);
    }

    boolean init = false;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus && !init) {
            init = true;
            if (d != null) {
                int i = 0;
                for (BDataDictionaryEntity b : bDataDictionaryEntities) {
                    if (b.getDValue().equals(d.getType())) {
                        spinner.setSelection(i);
                        break;
                    }
                    i++;
                }
                spinner2.setSelection(d.getRange());
                projectName.setText(d.getName());
                datas.addAll(session.getDMaterialModelItemEntityDao().queryBuilder().where(
                        DMaterialModelItemEntityDao.Properties.ModelGuid.eq(d.getGuid())
                        , DMaterialModelItemEntityDao.Properties.Datastate.notEq("删除")
                ).list());
                adapter.notifyDataSetChanged();
            }
        }
    }

    @OnClick({R.id.right_save, R.id.add_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_save:
                save();
                break;
            case R.id.add_button:
                DBUtils.addMaterial(this, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            int i = -1;
            if (requestCode == 2) {
                i = datas.indexOf(dm);
                datas.remove(dm);
            }
            List<BMaterialEntity> bMaterialEntities = (List<BMaterialEntity>) data.getSerializableExtra("material");
            for (BMaterialEntity b : bMaterialEntities) {
                setD(b, i);
            }
            adapter.notifyDataSetChanged();
        }
    }

    void setD(BMaterialEntity b, int i) {
        DMaterialModelItemEntity d = new DMaterialModelItemEntity();
        d.setDatastate("新增");
        d.setGuid(UUID.randomUUID().toString());
        d.setMaterialGuid(b.getGuid());
        d.setModelGuid(guid);
        d.setCount(b.getmCount());
        if (i != -1)
            datas.add(i, d);
        else
            datas.add(d);
    }

    private void save() {
        if (d == null) {
            d = new DMaterialModelEntity();
            d.setGuid(guid);
            d.setDatastate("新增");
            d.setCreateId(LoginInfo.getInfo(context).getUserId());
        } else {
            d.setDatastate("修改");
        }
        String name = getText(projectName);
        if (!TestingUtils.isEmpty(context, name, "模块名称")) return;
        d.setName(name);
        d.setRange(ranges.indexOf(adapter2.getSelectedItem()));
        d.setType(adapter1.getSelectedItem().getDValue());
        if (datas.size() == 0) {
            showMsg("材料不能为空");
            return;
        }
        session.getDMaterialModelItemEntityDao().insertOrReplaceInTx(datas);
        for (DMaterialModelItemEntity d : deleteDatas) {
            d.setDatastate("删除");
        }
        session.getDMaterialModelItemEntityDao().updateInTx(deleteDatas);
        String content = "";
        for (DMaterialModelItemEntity d : datas) {
            BMaterialEntity load = session.getBMaterialEntityDao().load(d.getMaterialGuid());
            content += load.getMName() + "( " + d.getCount() + " );\n";
        }
        d.setContent(content);
        session.getDMaterialModelEntityDao().insertOrReplaceInTx(d);
        finish();
    }

}
